﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CoreLibrary {

    public sealed class StringUtil {
        
        public static string SubString(string s, int beginIndex, int endIndex) {
            if (s == null)
                return null;
            beginIndex = Math.Max(beginIndex, 0);
            if (beginIndex > s.Length || endIndex < beginIndex)
                return string.Empty;
            if (endIndex > s.Length)
                return s.Substring(beginIndex);

            return s.Substring(beginIndex, endIndex - beginIndex);
        }

        public static string Join<T>(String glue, ICollection<T> c) {
            return Join(glue, c, false);
        }

        public static string Join<T>(string glue, ICollection<T> c, bool ignoreNullOrEmpty) {
            if (c == null) {
                throw new NullReferenceException();
            }

            if (c.Count == 0) {
                return string.Empty;
            }

            var iter = c.GetEnumerator();
            iter.MoveNext();

            var buf = new StringBuilder(100);
            buf.Append(Util.GetString(iter.Current));

            while (iter.MoveNext()) {
                var next = Util.GetString(iter.Current, null);
                if (string.IsNullOrEmpty(next)) {
                    if (ignoreNullOrEmpty) {
                        continue;
                    }
                    next = string.Empty;
                }

                if (glue != null) {
                    buf.Append(glue);
                }
                buf.Append(next);
            }
            return buf.ToString();
        }

        public static string Join<T>(string glue, ICollection<T> c, Func<T, string> converter) {
            if (c == null) {
                throw new NullReferenceException("The input collection in Join is null.");
            }

            if (c.Count == 0) {
                return string.Empty;
            }

            var iter = c.GetEnumerator();
            iter.MoveNext();

            var buf = new StringBuilder(c.Count * 30);
            buf.Append(Util.GetString(converter(iter.Current)));

            while (iter.MoveNext()) {
                var next = Util.GetString(converter(iter.Current));
                if (glue != null) {
                    buf.Append(glue);
                }
                buf.Append(next);
            }
            return buf.ToString();
        }

        public static string[] Split(char seperator, string input) {
            return input.Split(seperator);
        }

    }
}